package web.admin.shop;


import domain.shop.PayMethod;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.TextArea;
import org.apache.wicket.markup.html.form.TextField;
import org.apache.wicket.markup.html.link.Link;
import org.apache.wicket.markup.html.panel.Panel;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.LoadableDetachableModel;
import org.apache.wicket.model.PropertyModel;
import org.apache.wicket.spring.injection.annot.SpringBean;
import service.facade.admin.ShopAdminService;
import web.admin.components.TinyMceBehavior;

import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * Provides settings of particular pay method
 */
public final class PayMethodPanel extends Panel {

    @SpringBean
    private ShopAdminService shopAdminService;
    private final IModel<PayMethod> payMethodModel;
    private static Logger logger = Logger.getLogger(PayMethodPanel.class.getName());

    public PayMethodPanel(String id, final Long pageId, final PayMethodAdminPanel parent) {
        super(id);
        payMethodModel = new LoadableDetachableModel<PayMethod>() {

            @Override
            protected PayMethod load() {
                return shopAdminService.findPayMethodById(pageId);
            }
        };
        add(new Form<PayMethod>("form", payMethodModel) {

            {
                add(new TextField("name", new PropertyModel(payMethodModel, "name")).setRequired(true));
                final TextArea textArea = new TextArea("methodDescription", new PropertyModel(payMethodModel, "methodDescription"));
                textArea.add(new TinyMceBehavior(true));
                add(textArea);
            }

            @Override
            protected void onSubmit() {
                try {
                    shopAdminService.updatePayMethod(payMethodModel.getObject());
                    info(getLocalizer().getString("saved", this));

                } catch (Exception e) {
                    logger.log(Level.SEVERE, null, e);
                    getSession().error(getLocalizer().getString("system.error", this));

                }
            }
        });

        add(new Form("actions") {

            {
                add(new Link("delete") {

                    @Override
                    public void onClick() {
                        shopAdminService.deletePayMethod(payMethodModel.getObject());
                        parent.replacePanelToEmpty();
                    }
                });
            }
        });
    }


}
